/*
 * @Author: NJ_1098 xiabaoxin
 * @Date: 2025-02-12 10:35:24
 * @LastEditors: NJ_1098 xiabaoxin
 * @LastEditTime: 2025-02-14 17:11:45
 * @Description: 公共控制层
 */
const svgCaptcha = require("svg-captcha");
const upload = require("../utils/upload");
const CommonUtils = require("../utils/common.js");
const {
  CAPTCHA_TYPE,
  CAPTCHA_LENGTH,
  CAPTCHA_LINE_COUNT,
  CAPTCHA_HAS_COLOR,
  CAPTCHA_BG_COLOR,
} = require("../config/config.default");
const { systemError } = require("../constant/index.js");

class PublicController {
  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 文件上传（身份认证）
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async upload(ctx, next) {
    if (!ctx.request.files) {
      console.error("空文件");
      return ctx.app.emit("error", noFileError, ctx);
    }
    try {
      let url;
      if (Array.isArray(ctx.request.files.file)) {
        const filesUrl = [];
        // 多个文件
        for (let index in ctx.request.files.file) {
          const item = ctx.request.files.file[index];
          const itemRes = await upload(item);
          filesUrl.push(itemRes);
        }
        url = filesUrl;
      } else {
        const { file } = ctx.request.files;
        const res = await upload(file);
        url = [res];
      }
      ctx.body = {
        code: "00000",
        msg: "请求成功",
        data: {
          fileUrls: url,
          uid: ctx.state.userInfo.uid,
        },
      };
    } catch (err) {
      console.error("上传文件失败", err);
      return ctx.app.emit("error", err, ctx);
    }
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 文件上传（无需身份认证）
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async uploadWithoutToken(ctx, next) {
    if (!ctx.request.files) {
      console.error("空文件");
      return ctx.app.emit("error", noFileError, ctx);
    }
    try {
      let url;
      if (Array.isArray(ctx.request.files.file)) {
        const filesUrl = [];
        // 多个文件
        for (let index in ctx.request.files.file) {
          const item = ctx.request.files.file[index];
          const itemRes = await upload(item);
          filesUrl.push(itemRes);
        }
        url = filesUrl;
      } else {
        const { file } = ctx.request.files;
        const res = await upload(file);
        url = [res];
      }
      ctx.body = {
        code: "00000",
        msg: "请求成功",
        data: url,
      };
    } catch (err) {
      console.error("上传文件失败", err);
      return ctx.app.emit("error", err, ctx);
    }
  }

  /**
   * @author: NJ_1098 xiabaoxin
   * @description: 生成验证码
   * @param {*} ctx
   * @param {*} next
   * @return {*}
   */
  static async getCaptcha(ctx, next) {
    try {
      let captcha;
      if (CAPTCHA_TYPE === "0") {
        captcha = svgCaptcha.create({
          size: CAPTCHA_LENGTH, // 验证码长度
          ignoreChars: "0o1iI", // 排除易混淆字符
          noise: CAPTCHA_LINE_COUNT, // 干扰线条的数量
          color: CAPTCHA_HAS_COLOR, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
          background: CAPTCHA_BG_COLOR, // 验证码图片背景颜色
        });
      } else {
        captcha = svgCaptcha.createMathExpr({
          mathMin: 1, // 计算数字的最小值
          mathMax: 50, // 计算数字的最大值
          noise: CAPTCHA_LINE_COUNT,
          color: CAPTCHA_HAS_COLOR,
          background: CAPTCHA_BG_COLOR,
        });
      }
      const iv = CommonUtils.encrypt(captcha.text);
      const base64Svg = Buffer.from(captcha.data).toString("base64");
      const url = `data:image/svg+xml;base64,${base64Svg}`;
      ctx.body = {
        code: "00000",
        msg: "请求成功",
        data: {
          iv,
          url,
        },
      };
    } catch (e) {
      console.log(e);
      systemError.data = e.toString();
      ctx.app.emit("error", systemError, ctx);
    }
  }
}

module.exports = PublicController;
